<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人姓名" prop="assigneeName">
        <el-input
          v-model="queryParams.assigneeName"
          placeholder="请输入负责人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.task_status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['task:maintask:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['task:maintask:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['task:maintask:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['task:maintask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="maintaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务ID" align="center" prop="taskId" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_priority" :value="scope.row.priority"/>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="dueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人姓名" align="center" prop="assigneeName" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['task:maintask:edit']"
            :disabled="scope.row.editDisabled"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['task:maintask:remove']"
            :disabled="scope.row.deleteDisabled"
          >删除</el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleReceive(scope.row)"
            v-hasPermi="['task:maintask:edit']"
          >接收</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-paperclip"
            @click="handleAttachment(scope.row)"
            v-hasPermi="['task:maintask:query']"
          >附件</el-button>

          <el-tooltip v-if="scope.row.editDisabled" content="存在已接收的子任务，仅可编辑部分信息" placement="top">
            <i class="el-icon-warning" style="color: #E6A23C; margin-left: 5px;"></i>
          </el-tooltip>
          <el-tooltip v-if="scope.row.deleteDisabled" content="存在已接收的子任务，无法删除" placement="top">
            <i class="el-icon-warning" style="color: #F56C6C; margin-left: 5px;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改主任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="!isFullEditable && form.taskId" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" :disabled="!isFullEditable && form.taskId">
            <el-option
              v-for="dict in dict.type.task_priority"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间" prop="dueDate">
          <el-date-picker clearable
            v-model="form.dueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="负责人" prop="assigneeName">
          <el-select v-model="form.assigneeId" placeholder="请选择负责人" @change="handleAssigneeChange" :disabled="!isFullEditable && form.taskId">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">子任务信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSubTask">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSubTask">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="subTaskList" :row-class-name="rowSubTaskIndex" @selection-change="handleSubTaskSelectionChange" ref="subTask">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="子任务名称" prop="subTaskName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.subTaskName" placeholder="请输入子任务名称" />
            </template>
          </el-table-column>
          <el-table-column label="子任务描述" prop="description" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.description" placeholder="请输入子任务描述" />
            </template>
          </el-table-column>
          <el-table-column label="负责人" prop="assigneeId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.assigneeId" placeholder="请选择负责人" @change="handleSubTaskAssigneeChange(scope.row)">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.sub_task_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 任务附件对话框 -->
    <el-dialog :title="'任务附件 - ' + (form.taskName || '')" :visible.sync="attachmentOpen" width="800px" append-to-body>
      <task-attachment
        :task-id="form.taskId"
        :task-type="0"
        :disabled="!form.taskId"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="attachmentOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaintask, getMaintask, delMaintask, addMaintask, updateMaintask, checkTaskEditable, checkTaskDeletable, getSubTaskStatus, receiveMainTask } from "@/api/task/maintask"
import { listUser } from "@/api/system/user"
import TaskAttachment from "@/components/TaskAttachment"

export default {
  name: "Maintask",
  components: {
    TaskAttachment
  },
  dicts: ['task_priority', 'task_status', 'sub_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSubTask: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主任务表格数据
      maintaskList: [],
      // 子任务表格数据
      subTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前任务是否可完全编辑
      isFullEditable: true,
      // 当前任务的子任务状态信息
      subTaskStatusInfo: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        assigneeName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 用户列表
      userList: [],
      // 定时刷新器
      refreshTimer: null,
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "change" }
        ],
        assigneeId: [
          { required: true, message: "负责人不能为空", trigger: "change" }
        ]
      },
      // 任务附件对话框
      attachmentOpen: false
    }
  },
  created() {
    this.getList()
    this.getUserList()
    // 设置定时刷新，每30秒自动刷新一次任务状态
    this.refreshTimer = setInterval(() => {
      this.getList()
    }, 30000)
  },
  beforeDestroy() {
    // 清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  methods: {
    /** 获取用户列表 */
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows
      })
    },
    /** 查询主任务列表 */
    async getList() {
      this.loading = true
      try {
        const response = await listMaintask(this.queryParams)
        this.maintaskList = response.rows
        this.total = response.total
        
        // 为每个任务检查编辑和删除权限
        for (let task of this.maintaskList) {
          try {
            const editableRes = await checkTaskEditable(task.taskId)
            const deletableRes = await checkTaskDeletable(task.taskId)
            task.editDisabled = !editableRes.data
            task.deleteDisabled = !deletableRes.data
          } catch (error) {
            console.error(`检查任务${task.taskId}权限失败:`, error)
            task.editDisabled = false
            task.deleteDisabled = false
          }
        }
        
        this.loading = false
      } catch (error) {
        console.error('获取任务列表失败:', error)
        this.loading = false
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskName: null,
        description: null,
        priority: 1,
        dueDate: null,
        assigneeId: null,
        assigneeName: null,
        status: 0,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        subTaskList: []
      }
      this.subTaskList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 负责人选择变化 */
    handleAssigneeChange(userId) {
      const user = this.userList.find(u => u.userId === userId)
      if (user) {
        this.form.assigneeName = user.nickName
      }
    },
    /** 子任务负责人选择变化 */
    handleSubTaskAssigneeChange(row) {
      const user = this.userList.find(u => u.userId === row.assigneeId)
      if (user) {
        row.assigneeName = user.nickName
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加主任务"
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      const taskId = row.taskId || this.ids
      
      try {
        // 获取任务详情
        const response = await getMaintask(taskId)
        this.form = response.data
        this.subTaskList = response.data.subTaskList
        
        // 检查编辑权限
        const editableRes = await checkTaskEditable(taskId)
        this.isFullEditable = editableRes.data
        
        // 获取子任务状态信息
        const statusRes = await getSubTaskStatus(taskId)
        this.subTaskStatusInfo = statusRes.data
        
        this.open = true
        this.title = this.isFullEditable ? "修改主任务" : "修改主任务（受限编辑）"
        
        if (!this.isFullEditable) {
          this.$message.warning('该任务存在已接收的子任务，仅可编辑描述、截止时间等非关键信息')
        }
      } catch (error) {
        console.error('获取任务信息失败:', error)
        this.$modal.msgError('获取任务信息失败')
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.subTaskList = this.subTaskList
          if (this.form.taskId != null) {
            updateMaintask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMaintask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const taskIds = row.taskId || this.ids
      
      try {
        // 检查删除权限
        const deletableRes = await checkTaskDeletable(taskIds)
        if (!deletableRes.data) {
          this.$modal.msgError('该任务存在已接收的子任务，无法删除')
          return
        }
        
        this.$modal.confirm('是否确认删除主任务编号为"' + taskIds + '"的数据项？').then(function() {
          return delMaintask(taskIds)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      } catch (error) {
        console.error('检查删除权限失败:', error)
        this.$modal.msgError('检查删除权限失败')
      }
    },
	/** 子任务序号 */
    rowSubTaskIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 子任务添加按钮操作 */
    handleAddSubTask() {
      let obj = {
        subTaskName: "",
        description: "",
        assigneeId: null,
        assigneeName: "",
        status: 0
      }
      this.subTaskList.push(obj)
    },
    /** 删除子任务按钮操作 */
    handleDeleteSubTask() {
      if (this.checkedSubTask.length == 0) {
        this.$modal.msgError("请至少选择一条子任务进行删除");
        return;
      }
      this.checkedSubTask.sort((a, b) => b - a); // 从大到小排序索引
      this.checkedSubTask.forEach(index => {
        this.subTaskList.splice(index - 1, 1);
      });
    },
    /** 复选框选中数据 */
    handleSubTaskSelectionChange(selection) {
      this.checkedSubTask = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('task/mainTask/export', {
        ...this.queryParams
      }, `maintask_${new Date().getTime()}.xlsx`)
    },
    /** 接收主任务按钮操作 */
    handleReceive(row) {
      this.$modal.confirm('是否确认接收任务"' + row.taskName + '"？').then(() => {
        return receiveMainTask(row.taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("接收任务成功");
      }).catch(() => {});
    },
    /** 附件按钮操作 */
    handleAttachment(row) {
      this.form = row
      this.attachmentOpen = true
    },
  }
}
</script>
